<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 6. 验证哥德巴赫猜想。一个偶数可以拆分成两个质数之和。

    // 返回该数以前的所有质数
    function primeNumber (num) {
      if (typeof(num) !== 'number' || num % 1 !== 0) throw new Error('请传入整数')
      var arr = []
      for (var i = 2; i < num; i++) {
        if (isPrime(i)) arr.push(i)
      }
      return arr
    }

    // 判断是否为质数
    function isPrime (num) {
      if (typeof(num) !== 'number' || num % 1 !== 0 || num <= 1) throw new Error('请传入大于1的整数')
      if (num === 2) return true
      var flag = true
      for (var i = 2; i < num; i++) {
        if (num % i === 0) flag = false
      }
      return flag
    }

    // 遍历质数数组任意两数求和
    function goldbach (num) {
      if (typeof(num) !== 'number' || num % 2 !== 0 || num < 4) throw new Error('请传入大于4偶数')
      var arr = primeNumber(num)
      for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr.length; j++) {
          if (arr[i] + arr[j] === num) return true
        }
      }
      return false
    }
    console.log(goldbach(8)) // true
  </script>
</body>
</html>